<template>
  <div class="admin-container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="用户管理" name="users">
        <el-table :data="userList" style="width: 100%" v-loading="loading">
          <el-table-column prop="user_id" label="ID" width="80" />
          <el-table-column prop="username" label="用户名" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="created_at" label="注册时间" width="180">
            <template #default="scope">
              {{ new Date(scope.row.created_at).toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                {{ scope.row.status === 1 ? '正常' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button
                :type="scope.row.status === 1 ? 'danger' : 'success'"
                size="small"
                @click="handleUserStatusChange(scope.row)"
              >
                {{ scope.row.status === 1 ? '禁用' : '启用' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalUsers"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next"
          class="pagination"
        />
      </el-tab-pane>
      
      <el-tab-pane label="新闻管理" name="news">
        <div class="news-header">
          <el-button type="primary" @click="showCreateDialog">创建新闻</el-button>
        </div>
        
        <el-table :data="newsList" style="width: 100%" v-loading="loading">
          <el-table-column prop="news_id" label="ID" width="80" />
          <el-table-column prop="title" label="标题" />
          <el-table-column prop="category" label="分类" width="120" />
          <el-table-column prop="reporter_name" label="记者" width="120" />
          <el-table-column prop="publish_time" label="发布时间" width="180">
            <template #default="scope">
              {{ new Date(scope.row.publish_time).toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column prop="read_count" label="阅读数" width="100" />
          <el-table-column prop="like_count" label="点赞数" width="100" />
          <el-table-column prop="comment_count" label="评论数" width="100" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row.news_id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next"
          class="pagination"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- 新闻表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑新闻' : '创建新闻'"
      width="50%"
    >
      <el-form :model="newsForm" label-width="100px">
        <el-form-item label="标题" required>
          <el-input v-model="newsForm.title" />
        </el-form-item>
        <el-form-item label="内容" required>
          <el-input
            v-model="newsForm.content"
            type="textarea"
            :rows="6"
          />
        </el-form-item>
        <el-form-item label="分类" required>
          <el-select v-model="newsForm.category" placeholder="请选择分类">
            <el-option label="政治" value="政治" />
            <el-option label="经济" value="经济" />
            <el-option label="文化" value="文化" />
            <el-option label="科技" value="科技" />
            <el-option label="体育" value="体育" />
          </el-select>
        </el-form-item>
        <el-form-item label="记者" required>
          <el-input v-model="newsForm.reporter_name" />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleImageChange"
          >
            <img v-if="newsForm.image" :src="URL.createObjectURL(newsForm.image)" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '../config/axios'

const router = useRouter()
const newsList = ref([])
const userList = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const loading = ref(false)
const newsFormRef = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const totalUsers = ref(0)
const activeTab = ref('users')
const total = ref(0)

const newsForm = ref({
  title: '',
  content: '',
  reporter_name: '',
  category: '',
  image: null
})

const rules = {
  title: [
    { required: true, message: '请输入新闻标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度应在 2 到 100 个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入新闻内容', trigger: 'blur' },
    { min: 10, message: '内容长度不能少于 10 个字符', trigger: 'blur' }
  ],
  reporter_name: [
    { required: true, message: '请输入记者姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度应在 2 到 20 个字符之间', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取新闻列表
const fetchNewsList = async () => {
  try {
    loading.value = true
    const response = await axios.get('/api/news', {
      params: {
        page: currentPage.value,
        limit: pageSize.value
      }
    })
    newsList.value = response.data.data.news
    total.value = response.data.data.total
  } catch (error) {
    console.error('获取新闻列表失败:', error)
    ElMessage.error('获取新闻列表失败')
  } finally {
    loading.value = false
  }
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    loading.value = true
    const response = await axios.get('/api/users', {
      params: {
        page: currentPage.value,
        limit: pageSize.value
      }
    })
    userList.value = response.data.data
    totalUsers.value = response.data.total
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 处理用户状态变更
const handleUserStatusChange = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要${user.status === 1 ? '禁用' : '启用'}该用户吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await axios.put(`/api/users/${user.user_id}/status`, {
      status: user.status === 1 ? 0 : 1
    })

    ElMessage.success('状态更新成功')
    fetchUserList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新用户状态失败:', error)
      ElMessage.error('更新用户状态失败')
    }
  }
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  if (activeTab.value === 'users') {
    fetchUserList()
  } else {
    fetchNewsList()
  }
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  if (activeTab.value === 'users') {
    fetchUserList()
  } else {
    fetchNewsList()
  }
}

// 监听标签页切换
watch(activeTab, (newTab) => {
  if (newTab === 'users') {
    fetchUserList()
  } else {
    fetchNewsList()
  }
})

// 显示创建新闻对话框
const showCreateDialog = () => {
  resetForm()
  dialogVisible.value = true
}

// 处理编辑新闻
const handleEdit = (row) => {
  isEdit.value = true
  newsForm.value.news_id = row.news_id
  newsForm.value.title = row.title
  newsForm.value.content = row.content
  newsForm.value.category = row.category
  newsForm.value.reporter_name = row.reporter_name
  newsForm.value.image = null
  dialogVisible.value = true
}

// 处理删除新闻
const handleDelete = async (newsId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条新闻吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await axios.delete(`/api/news/${newsId}`)
    ElMessage.success('新闻删除成功')
    fetchNewsList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除新闻失败:', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

// 处理提交表单
const handleSubmit = async () => {
  try {
    const formData = new FormData()
    formData.append('title', newsForm.value.title)
    formData.append('content', newsForm.value.content)
    formData.append('category', newsForm.value.category)
    formData.append('reporter_name', newsForm.value.reporter_name)
    if (newsForm.value.image) {
      formData.append('image', newsForm.value.image)
    }

    if (isEdit.value) {
      // 编辑新闻
      await axios.put(`/api/news/${newsForm.value.news_id}`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      ElMessage.success('新闻更新成功')
    } else {
      // 创建新闻
      await axios.post('/api/news', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      ElMessage.success('新闻创建成功')
    }

    dialogVisible.value = false
    fetchNewsList()
  } catch (error) {
    console.error('提交新闻失败:', error)
    ElMessage.error(error.response?.data?.message || '操作失败')
  }
}

const handleImageChange = (file) => {
  newsForm.value.image = file.raw
}

const resetForm = () => {
  newsForm.value.title = ''
  newsForm.value.content = ''
  newsForm.value.category = ''
  newsForm.value.reporter_name = ''
  newsForm.value.image = null
  isEdit.value = false
}

// 初始化
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.admin-container {
  padding: 20px;
}

.news-header {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style> 